package com.guestbook.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.entity.Guestbook;
import com.guestbook.biz.GuestbookBiz;

@Controller
@Scope(value="prototype")
@RequestMapping(value="/secure")
public class AdminController
{
    @Autowired
    private GuestbookBiz guestbookBiz;
    
    @RequestMapping(value="/deleteGuestbook/{id}")
    public String delete(@PathVariable("id") Integer id)
    {
        guestbookBiz.deleteById(id);
        return "redirect:/secure/list.action";
    }
    
    @RequestMapping(value="/list")
    public String list(Map<String, Object> model)
    {
        List<Guestbook> guestbookList = guestbookBiz.findAllOrderById();
        model.put("guestbookList", guestbookList);
        return "secure/admindisplay";
    }
    
    @RequestMapping(value="/edit/{id}",method=RequestMethod.GET)
    public String edit(Map<String, Object> model,@PathVariable("id") Integer id)
    {
        model.put("guestbook", guestbookBiz.findById(id));
        return "secure/editor";
    }
    @RequestMapping(value="/edit/{id}",method=RequestMethod.POST)
    public String update(Map<String, Object> model,@PathVariable("id") Integer id,Guestbook guestbook)
    {
        guestbookBiz.update(guestbook);
        model.put("guestbook", guestbook);
        return "secure/updateresult";
    }
    
    @InitBinder
    public void initBinder(ServletRequestDataBinder binder)
    {
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), false));
    }
} 
